<script setup>
import { Edit, Delete } from "@element-plus/icons-vue";

import {
  courseTypePageListService,
  courseTypeAddService,
  courseTypeUpdateService,
  courseTypeDeleteService,
  CourseTypeBatchdelService,
  expCourseTypeServer,
  CourseTypeUploadService,
} from "@/api/course.js";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

//用户搜索时的关键字
const input = ref("");
//课程分类列表数据模型
const courseTypeList = ref([]);

//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(20); //总条数
const pageSize = ref(10); //每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  getCourseTypePageList();
};
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  getCourseTypePageList();
};

//获取课程分类列表数据
const getCourseTypePageList = async () => {
  //设置查询参数
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    // 有值就传 ，否则null
    name: input.value ? input.value : null,
  };
  let result = await courseTypePageListService(params);
  //刷新列表显示
  courseTypeList.value = result.data.items;
  total.value = result.data.total;
};

getCourseTypePageList();

//控制抽屉是否显示
const visibleDrawer = ref(false);
//添加课程分类表单数据模型
const CourseTypeModel = ref({
  name: "",
  description: "",
});

//创建课程分类
const courseTypeAdd = async () => {
  //调用接口
  let result = await courseTypeAddService(CourseTypeModel.value);
  //提示
  ElMessage.success(result.message ? result.message : "添加成功");
  //关闭抽屉
  visibleDrawer.value = false;
  //刷新列表
  getCourseTypePageList();
};
//显示抽屉
const showDialog = (row) => {
  CourseTypeModel.value = row;
  visibleDrawer.value = true;
  isAdd.value = false;
};
//清空抽屉
const clearDialog = () => {
  CourseTypeModel.value = {};
};
//发送修改请求
const courseTypeUpdate = async () => {
  //调用接口
  let result = await courseTypeUpdateService(CourseTypeModel.value);
  //提示
  ElMessage.success(result.message ? result.message : "修改成功");
  //关闭抽屉
  visibleDrawer.value = false;
  //刷新列表
  getCourseTypePageList();
};

//控制按钮是创建还是修改
const isAdd = ref(true);

//删除课程分类请求
const courseTypeDelete = async (row) => {
  //弹框询问
  let confirm = await ElMessageBox.confirm(
    "此操作将永久删除该分类, 是否继续?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  );
  //确认删除
  if (confirm) {
    //调用接口
    let result = await courseTypeDeleteService(row.id);
    ElMessage.success(result.message ? result.message : "删除成功");
    //刷新列表
    getCourseTypePageList();
  }
};
const multipleSelection = ref([]); // 多选数据
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const delBatch = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      let result = await CourseTypeBatchdelService(multipleSelection.value);
      ElMessage.success(result.msg ? result.msg : "删除成功");
      getCourseTypePageList();
    })
    .catch(() => {});
};
//导出报表函数
const exp = async () => {
  let result = await expCourseTypeServer();
  ElMessage.success(result.msg ? result.msg : "下载成功");
};

// 文件输入框引用
const dialogVisible = ref(false);
const inputFile = ref();

// 触发文件选择对话框
const handleImportClick = () => {
  dialogVisible.value = true;
};

// 处理文件选择
const handleFileChange = (file, fileList) => {
  if (fileList.length > 1) {
    fileList.shift(); // 移除第一个文件，保留最新的文件
  }
  inputFile.value = fileList;
};

// 上传文件
const uploadFile = async () => {
  if (inputFile.value.length === 0) {
    ElMessage.warning("请选择一个文件");
    return;
  }

  const file = inputFile.value[0].raw;
  try {
    let result = await CourseTypeUploadService(file);
    ElMessage.success(result.message ? result.message : "上传成功");
    dialogVisible.value = false;
    getCourseTypePageList();
  } catch (error) {
    ElMessage.error("上传失败: " + error.message);
  }
};
</script>

<template>
  <el-card class="page-container transparent-card">
    <template #header>
      <div class="header">
        <div class="extra">
          <el-button
            type="primary"
            @click="
              visibleDrawer = true;
              clearDialog();
              isAdd = true;
            "
            >添加分类</el-button
          >
          <el-button type="danger" @click="delBatch()">批量删除</el-button>
          <el-button type="success" @click="exp()">导出报表</el-button>
          <el-button type="primary" @click="handleImportClick"
            >导入excel</el-button
          >
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item>
        <el-input
          v-model="input"
          style="width: 240px"
          placeholder="请输入课程分类标题"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getCourseTypePageList"
          >搜索</el-button
        >
        <el-button @click="input = ''">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table
      :data="courseTypeList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="table"
      :row-key="(row) => row.id"
    >
      <!-- prop要与后端传过来的值保持一致。 -->
      <el-table-column width="100" type="selection" :reserve-selection="true">
      </el-table-column>
      <el-table-column
        label="分类标题"
        width="400"
        prop="name"
      ></el-table-column>
      <el-table-column label="创建时间" prop="createTime"> </el-table-column>
      <el-table-column label="修改时间" prop="updateTime"> </el-table-column>
      <el-table-column label="创建者" prop="createUser"> </el-table-column>
      <el-table-column label="最后修改者" prop="updateUser"> </el-table-column>
      <el-table-column label="描述" prop="description"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="showDialog(row)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="courseTypeDelete(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 抽屉 -->
    <el-drawer
      v-model="visibleDrawer"
      title="添加课程分类"
      direction="rtl"
      size="50%"
    >
      <!-- 添加文章表单 -->
      <el-form :model="CourseTypeModel" label-width="100px">
        <el-form-item label="分类名称">
          <el-input
            v-model="CourseTypeModel.name"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="CourseTypeModel.description"
            placeholder="请输入描述"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="isAdd ? courseTypeAdd() : courseTypeUpdate()"
          >
            {{ isAdd ? "创建" : "更新" }}
          </el-button>
          <el-button type="info" @click="visibleDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 导入对话框 -->
    <el-dialog v-model="dialogVisible" title="导入Excel文件" width="30%">
      <el-upload
        ref="upload"
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="inputFile"
        accept=".xlsx, .xls"
        :show-file-list="true"
      >
        <template #trigger>
          <el-button type="primary">选取文件</el-button>
        </template>
        <el-button type="success" @click="uploadFile()">上传文件</el-button>
      </el-upload>
    </el-dialog>
  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
}

.transparent-card {
  background-color: rgba(255, 255, 255, 0.8); /* 半透明白色背景 */
  backdrop-filter: blur(0px); /* 模糊效果 */
  border-radius: 4px; /* 圆角 */
  padding: 20px; /* 内边距 */
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.el-select {
  width: 200px;
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>